package com.legal.service.user.impl;


import com.legal.service.user.RateLimitService;
import com.legal.service.user.SlidingWindowRateLimiter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 *  速率限流服务实现类
 * @author xiaopeng
 * @version 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RateLimitServiceImpl implements RateLimitService {

    private final SlidingWindowRateLimiter slidingWindowRateLimiter;

    /**
     * 滑动窗口限流检查-计数
     *
     * @param key         限流key
     * @param maxAttempts 最大尝试次数
     * @param windowSize  窗口大小
     * @return 是否允许
     */
    public boolean checkSlidingRateLimit(String key, int maxAttempts, Duration windowSize) {
        return slidingWindowRateLimiter.allowRequest(key, (int) windowSize.getSeconds(), maxAttempts);
    }

    /**
     * 滑动窗口预检查-不计数
     */
    public boolean peekSlidingRateLimit(String key, int maxAttempts, Duration windowSize) {
        return slidingWindowRateLimiter.peekRequest(key, (int) windowSize.getSeconds(), maxAttempts);
    }
}
